<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-button type="primary">添加角色</el-button>
      <!-- 角色列表区域 -->
      <template>
        <el-table :stripe="true" :data="rolelist" style="width: 100%">
          <el-table-column type="expand">
            <!-- 列表展开项目 -->
            <template v-slot="props">
              <el-row
                :class="['venter','bdbottom',i1 === 0? 'bdtop':'']"
                v-for="(item1,i1) in props.row.children"
                :key="item1.id"
              >
                <!-- 渲染一级权限 -->
                <el-col :span="5">
                  <el-tag closable @close='removeRightById(props.row,item1.id)'>{{item1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 渲染二级三级权限 -->
                <el-col :span="19">
                  <!-- 二级权限 -->
                  <el-row
                    :class="['venter', i2===0?'':'bdtop']"
                    v-for="(item2,i2) in item1.children"
                    :key="item2.id"
                  >
                    <el-col :span="6">
                      <el-tag type="success" closable @close='removeRightById(props.row,item2.id)'>{{item2.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!--  三级权限 -->
                    <el-col :span="13">
                      <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable @close='removeRightById(props.row,item3.id)'>{{item3.authName}}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
<!-- <pre>{{ props.row}}</pre> -->
            </template>
          </el-table-column>
          <el-table-column type="index" label="#" prop="id"></el-table-column>
          <el-table-column label="角色名称" prop="roleName"></el-table-column>
          <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
          <el-table-column label="操作">
            <template v-slot="scope">
                <el-button size="mini" type="primary"   icon="el-icon-edit">编辑</el-button>
                <el-button size="mini" type="danger"    icon="el-icon-delete">删除</el-button>
                <el-button size="mini" type="warning"   icon="el-icon-setting"    @click="showSetRightDialog(scope.row)">分配权限</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog
  title="提示"
  :visible.sync="setRightdialogVisible"
  width="30%"
  @close="setRightDiallogClosed">
  <!-- 树形控件 -->
  <el-tree show-checkbox :data="rightsList" :props="defaultProps" node-key="id" :default-expand-all="true" :default-checked-keys="defKeys" ref="treeRef"></el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRightdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
        // 角色列表数据
        rolelist: [],
        //  分配权限对话框的显示与隐藏
        setRightdialogVisible: false,
        // 所有权限的数据
        rightsList:[],
        // 树形控件属性绑定对象
        defaultProps:{
          children: 'children',
          label: 'authName'
        },
        // 默认选中的节点id值数组
        defKeys:[],
        // 将要选中分配权限的角色的id
        roleId:''
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
    //   console.log(res);
      this.rolelist = res.data;
    },
    // 根据Id删除对应权限
    async removeRightById (role,rightId){
        // 弹框是否确认删除对应权限
        const confirmReuslt = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)

        if (confirmReuslt !== 'confirm') {
            return this.$message({
            type: 'info',
            message: '已取消删除'
          })
        }
        console.log('确认了');
        const {data: res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if (res.meta.status !== 200) return this.$message.error('删除权限失败')
        console.log(res);
        // 返回删除后的数据
        role.children = res.data
    },
    // 分配权限对话框
    async showSetRightDialog (role) { 
        this.roleId = role.id
        // 获取分配权限的数据请求
        const {data: res} = await this.$http.get('rights/tree')
        console.log(res)
        if (res.meta.status !== 200) {
            return this.$message.error('获取数据失败')
        }
        this.rightsList = res.data
        this.getLeafKeys(role,this.defKeys)
        this.setRightdialogVisible = true
    },
    // 通过递归的形式，获取据说下所有的三级权限的id，并保存到defkeys数组中
    getLeafKeys(node,arr){
        // 如果当前node节点不包含children属性，则是三级节点
        if (!node.children) return arr.push(node.id)
        node.children.forEach(item=>this.getLeafKeys(item,arr))
    },
    // 监听分配权限对话框的关闭事件
    setRightDiallogClosed (){
        this.defKeys = []
    },
    async allotRights (){
        const keys = [
            //  获取已经选中的节点数组
            ...this.$refs.treeRef.getCheckedKeys(),
            ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        console.log(keys);
        const idStr = keys.join(',')
        const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
        console.log(res);
        if (res.meta.status !== 200){
            this.$message.error('更新失败')
        }
        this.$message.success('更新成功')
        this.setRightdialogVisible = false
        this.getRolesList();
    }
  }
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 10px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.venter {
    display: flex;
    align-items: center;
}
// .el-row {
//     border-top: 1px solid #eee;
// }
</style>
